package com.hernie.piggymall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author HuangJp
 * @Date 2022/5/9
 * @Description 自定义feign拦截器
 */
@Configuration
public class PiggyFeignConfig {

    /**
     * 解决feign远程调用丢失请求头的问题
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // RequestContextHolder拿到刚进来的这个请求,利用ThreadLocal
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest(); // 老请求
                    if (request != null) {
                        // 同步请求头数据，主要同步cookie
                        // 从老请求中获取请求头
                        String cookie = request.getHeader("Cookie");
                        // 设置新请求,给新请求同步上老请求的cookie
                        requestTemplate.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}
